package com.xiaohao.employee_attendance.service;

import com.xiaohao.employee_attendance.bean.User;
import com.xiaohao.employee_attendance.dao.DeptDao;
import com.xiaohao.employee_attendance.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;
import java.util.Optional;

/**
 * Created with IntelliJ IDEA.
 *
 * @author 小浩
 * @date 2019-03-04 15:32
 * @package com.xiaohao.employee_attendance.service
 * @description
 */
@Service
public class UserService {
    @Autowired
    UserDao userDao;
    @Autowired
    DeptDao deptDao;

    public List<User> findUserByName(String name) {
        List<User> userByName = userDao.findUserByName(name);
        return userByName;
    }

    public List<User> findAllUser() {
        List<User> all = userDao.findAll();
        return all;
    }

    public Page<User> findAllUserPage(int size, int page) {
        Page<User> all = userDao.findAll(PageRequest.of(page, size));
        return all;

    }

    public List<User> findUserByDept(String dept) {
        List<User> userByDepartmentId = userDao.findUserByDepartmentId(dept);
        return userByDepartmentId;
    }


    public List<User> findUserByNameAndDept(String name, String dept) {
        List<User> userByNameAndDepartmentId = userDao.findUserByNameAndDepartmentId(name, dept);
        return userByNameAndDepartmentId;
    }

    public User findUserByAccount(String account) {
        User userByAccount = userDao.findUserByAccount(account);
        return userByAccount;
    }

    public User findUserById(int id) {
        Optional<User> userByAccount = userDao.findById(id);
        return userByAccount.get();
    }

    @Transactional
    public User saveUser(User user) {
        return userDao.save(user);
    }

    @Transactional
    public int deleteUser(String account) {
        User user = userDao.findUserByAccount(account);
        deptDao.updateTotalNumberByName(user.getDepartmentId(), -1);
        int i = userDao.deleteUserByAccount(account);
        return i;
    }
}
